package cn.xiaopengstack.trigger.listener;

import cn.xiaopengstack.domain.activity.model.valobj.ActivitySkuStockKeyVO;
import cn.xiaopengstack.domain.activity.repository.IRaffleActivityRepository;
import cn.xiaopengstack.types.event.BaseEvent;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.annotation.SelectorType;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author jiangyangang
 */
@RocketMQMessageListener(
        topic = "activity_sku_stock_zero",
        consumerGroup = "jyg-big-marketing-group",
        selectorType = SelectorType.TAG,
        selectorExpression = "*"
)
@Component
@Slf4j
public class ActivitySkuStockZeroConsumer implements RocketMQListener<String> {

    @Resource
    private IRaffleActivityRepository activityRepository;

    @Override
    public void onMessage(String message) {
        try {
            BaseEvent.EventMessage<ActivitySkuStockKeyVO> messageVO = JSONObject.parseObject(message,
                    new TypeReference<BaseEvent.EventMessage<ActivitySkuStockKeyVO>>(){}.getType());

            // 清空库存
            activityRepository.clearActivitySkuStockDecrQueue(messageVO.getMessage());
            // 清空库存
            activityRepository.clearActivitySkuStock(messageVO.getMessage().getSku());
        } catch (Exception e) {
            log.error("监听活动sku库存消耗为0消息，消费失败 topic: {} message: {}", "activity_sku_stock_zero", message);

            throw e;
        }

    }
}
